use std::sync::Arc;
use std::collections::HashMap;
use warp::{Reply, Rejection};
use serde_json;
use chrono::Utc;
use tracing::{info, error, debug};

use crate::storage::DataStorage;
use crate::api::models::*;
use crate::write_handler::WriteHandler;
use crate::error::{ModbusCollectorError};

/// API处理器
#[derive(Debug, Clone)]
pub struct ApiHandlers {
    storage: DataStorage,
    write_handler: Option<std::sync::Arc<WriteHandler>>,
}

impl ApiHandlers {
    pub fn new(storage: DataStorage) -> Self {
        Self {
            storage,
            write_handler: None,
        }
    }
    
    /// 设置写处理器
    pub fn with_write_handler(mut self, write_handler: std::sync::Arc<WriteHandler>) -> Self {
        self.write_handler = Some(write_handler);
        self
    }
    
    /// 获取所有设备列表
    pub async fn get_devices(
        &self,
        query: QueryParams,
    ) -> std::result::Result<impl Reply, Rejection> {
        debug!("GET /api/devices with query: {:?}", query);
        
        let devices = self.storage.get_all_device_status().await;
        let device_models: Vec<DeviceStatusModel> = devices.into_iter()
            .map(DeviceStatusModel::from)
            .collect();
        
        let response = ApiResponse::success(device_models);
        Ok(warp::reply::json(&response))
    }
    
    /// 获取特定设备信息
    pub async fn get_device(
        &self,
        device_id: String,
    ) -> std::result::Result<impl Reply, Rejection> {
        debug!("GET /api/devices/{}", device_id);
        
        match self.storage.get_device_status(&device_id).await {
            Some(status) => {
                let model = DeviceStatusModel::from(status);
                let response = ApiResponse::success(model);
                Ok(warp::reply::json(&response))
            },
            None => {
                let response: ApiResponse<()> = ApiResponse::error(
                    format!("Device not found: {}", device_id)
                );
                Ok(warp::reply::json(&response))
            }
        }
    }
    
    /// 获取设备的最新数据点
    pub async fn get_device_data(
        &self,
        device_id: String,
        query: QueryParams,
    ) -> std::result::Result<impl Reply, Rejection> {
        debug!("GET /api/devices/{}/data with query: {:?}", device_id, query);
        
        let data_points = self.storage.get_device_latest_data(&device_id).await;
        let data_models: Vec<DataPointModel> = data_points.into_iter()
            .map(DataPointModel::from)
            .collect();
        
        let response = ApiResponse::success(data_models);
        Ok(warp::reply::json(&response))
    }
    
    /// 获取所有最新数据点
    pub async fn get_all_points(
        &self,
        query: QueryParams,
    ) -> std::result::Result<impl Reply, Rejection> {
        debug!("GET /api/points with query: {:?}", query);
        
        let data_points = self.storage.get_all_latest_data().await;
        let mut data_models: Vec<DataPointModel> = data_points.into_iter()
            .map(DataPointModel::from)
            .collect();
        
        // 可选的设备过滤
        if let Some(device_id) = &query.device_id {
            data_models.retain(|dp| &dp.device_id == device_id);
        }
        
        // 分页
        let page = query.page.unwrap_or(1);
        let page_size = query.page_size.unwrap_or(50).min(1000); // 最大1000条
        let total = data_models.len();
        
        let start = (page - 1) * page_size;
        let end = (start + page_size).min(total);
        
        let paginated_items = if start < total {
            data_models[start..end].to_vec()
        } else {
            Vec::new()
        };
        
        let paginated = PaginatedResponse::new(paginated_items, total, page, page_size);
        let response = ApiResponse::success(paginated);
        
        Ok(warp::reply::json(&response))
    }
    
    /// 获取特定点位数据
    pub async fn get_point(
        &self,
        point_id: String,
    ) -> std::result::Result<impl Reply, Rejection> {
        debug!("GET /api/points/{}", point_id);
        
        match self.storage.get_latest_data_point(&point_id).await {
            Some(data_point) => {
                let model = DataPointModel::from(data_point);
                let response = ApiResponse::success(model);
                Ok(warp::reply::json(&response))
            },
            None => {
                let response: ApiResponse<()> = ApiResponse::error(
                    format!("Point not found: {}", point_id)
                );
                Ok(warp::reply::json(&response))
            }
        }
    }
    
    /// 获取点位历史数据
    pub async fn get_point_history(
        &self,
        point_id: String,
        query: HistoryQuery,
    ) -> std::result::Result<impl Reply, Rejection> {
        debug!("GET /api/points/{}/history with query: {:?}", point_id, query);
        
        match self.storage.get_history_data(
            &point_id,
            query.start_time,
            query.end_time,
            query.limit,
        ).await {
            Ok(data_points) => {
                let data_models: Vec<DataPointModel> = data_points.into_iter()
                    .map(DataPointModel::from)
                    .collect();
                let response = ApiResponse::success(data_models);
                Ok(warp::reply::json(&response))
            },
            Err(e) => {
                error!("Failed to get history data: {}", e);
                let response: ApiResponse<()> = ApiResponse::error(
                    format!("Failed to get history data: {}", e)
                );
                Ok(warp::reply::json(&response))
            }
        }
    }
    
    /// 写入数据点
    pub async fn write_point(
        &self,
        request: WriteRequest,
    ) -> std::result::Result<impl Reply, Rejection> {
        debug!("POST /api/write with request: {:?}", request);
        
        match &self.write_handler {
            Some(handler) => {
                match handler.submit_write_request(request).await {
                    Ok(response) => {
                        Ok(warp::reply::json(&ApiResponse::success(response)))
                    },
                    Err(e) => {
                        error!("Write operation failed: {}", e);
                        let response = WriteResponse {
                            point_id: "unknown".to_string(),
                            success: false,
                            message: format!("Write operation failed: {}", e),
                            timestamp: Utc::now(),
                        };
                        Ok(warp::reply::json(&ApiResponse::success(response)))
                    }
                }
            },
            None => {
                let response = WriteResponse {
                    point_id: request.point_id,
                    success: false,
                    message: "Write handler not initialized".to_string(),
                    timestamp: Utc::now(),
                };
                Ok(warp::reply::json(&ApiResponse::success(response)))
            }
        }
    }

    /// 获取系统状态
    pub async fn get_system_status(&self) -> Result<impl Reply, Rejection> {
        debug!("GET /api/system/status");
        
        // 获取存储统计
        let storage_stats = match self.storage.get_statistics().await {
            Ok(stats) => stats,
            Err(e) => {
                error!("Failed to get storage statistics: {}", e);
                let response: ApiResponse<()> = ApiResponse::error(
                    format!("Failed to get system status: {}", e)
                );
                return Ok(warp::reply::json(&response));
            }
        };
        
        let system_status = SystemStatus {
            collector: CollectorStatusModel {
                running: true, // 简化实现
                worker_count: 4,
                active_tasks: 0,
            },
            storage: StorageStatusModel {
                memory_points: storage_stats.memory.latest_points_count,
                memory_usage_mb: storage_stats.memory.memory_usage_mb,
                persistent_enabled: storage_stats.persistent.is_some(),
                db_size_mb: storage_stats.persistent.map(|p| p.db_size_mb),
            },
            api: ApiStatusModel {
                port: 8080,
                websocket_connections: 0, // 将在WebSocket实现中更新
                requests_served: 0, // 可以添加计数器
            },
            uptime_seconds: 0, // 可以添加启动时间跟踪
        };
        
        let response = ApiResponse::success(system_status);
        Ok(warp::reply::json(&response))
    }
    
    /// 健康检查
    pub async fn health_check() -> std::result::Result<impl Reply, Rejection> {
        let health = HashMap::from([
            ("status".to_string(), "healthy".to_string()),
            ("timestamp".to_string(), Utc::now().to_rfc3339()),
        ]);
        
        let response = ApiResponse::success(health);
        Ok(warp::reply::json(&response))
    }
}

/// 错误处理
pub async fn handle_rejection(err: Rejection) -> std::result::Result<impl Reply, std::convert::Infallible> {
    let code;
    let message;
    
    if err.is_not_found() {
        code = warp::http::StatusCode::NOT_FOUND;
        message = "Not Found";
    } else if let Some(_) = err.find::<warp::filters::body::BodyDeserializeError>() {
        code = warp::http::StatusCode::BAD_REQUEST;
        message = "Invalid JSON body";
    } else if let Some(_) = err.find::<warp::reject::MethodNotAllowed>() {
        code = warp::http::StatusCode::METHOD_NOT_ALLOWED;
        message = "Method Not Allowed";
    } else {
        error!("Unhandled rejection: {:?}", err);
        code = warp::http::StatusCode::INTERNAL_SERVER_ERROR;
        message = "Internal Server Error";
    }
    
    let response: ApiResponse<()> = ApiResponse::error(message.to_string());
    let json = warp::reply::json(&response);
    
    Ok(warp::reply::with_status(json, code))
}